extends Node2D
class_name StateMachine

@export var ownerNode:Node2D

var currentStateDict:Dictionary = {}
var stateDict:Dictionary = {}
var stateArr:Array = []


func _ready():
	if ownerNode == null:
		ownerNode = get_parent()
	currentStateDict = {}
	stateDict = {}
	stateArr = []
	var childCount = get_child_count( )
	for index in range(childCount):
		var childStateNode = get_child(index)
		if childStateNode is StateBase:
			childStateNode.ownerNode = ownerNode
		stateDict[childStateNode.name] = childStateNode
		stateArr.append(childStateNode)
	

func run(delta):
	for key in currentStateDict.keys():
		var targetState = currentStateDict[key]
		targetState.run(delta)


func addState(stateName):
	print(ownerNode.name, " addState ", stateName)
	var targetState:StateBase = stateDict[stateName]
	if not currentStateDict.has(stateName):
		currentStateDict[stateName] = targetState
		targetState.enter()
	

func removeState(stateName):
	if not currentStateDict.has(stateName): return
	
	var targetState:StateBase = currentStateDict[stateName]
	if targetState != null:
		targetState.exit()
		currentStateDict.erase(stateName)
		print(ownerNode.name + " removeState ", stateName)


func clearAndAddState(stateName):
	for key in currentStateDict.keys():
		removeState(key)
	addState(stateName)
	

